<?php
require_once "./connectdb.php";
//$db
//首页获取帖子列表
function get_post_list(){
	global $db;
	$ps1=$db->prepare("SELECT * FROM `post` order by id desc");
	$ps1->execute();
	return $ps1->fetchAll();
}
// 获取帖子内容
function get_post($postid){
	global $db;
	$ps=$db->prepare("SELECT * FROM `post` WHERE `id`=?");
	$ps->execute(array($postid));
	$post_arr=$ps->fetch();
	if($post_arr !== false)
		return $post_arr;
	else
		return '';
}
// 获取评论列表
function get_comment_list($pid){
	global $db;
	$ps=$db->prepare("SELECT * FROM `comment` WHERE `postid`=?");
	$ps->execute(array($pid));
	$cmt_arr=$ps->fetchAll();
	if($cmt_arr !== false)
		return $cmt_arr;
	else
		return ''; 
}
// 插入主题帖子
function creat_post($post){
	global $db;
	$ps=$db->prepare("INSERT INTO `post`(title,contents,uid,creat_time) VALUES(?,?,?,?)");
	$ps->execute(array($post['title'],$post['content'],$post['uid'],$post['crtime']));

}
// fucntion checkPostIsOK(){
		
// }
// 插入评论贴子
function creat_comment($comment){
	global $db;
	$ps=$db->prepare("INSERT INTO `comment`(content,uid,postid) VALUES(?,?,?)");
	$ps->execute(array($comment['content'],$comment['uid'],$comment['pid']));
}
function get_username($uid){
	global $db;

	$ps6 = $db->prepare("SELECT username FROM `users` WHERE `id`=?");
	$ps6->execute(array($uid));
	$user = $ps6->fetch();

	if($user !== false)
		return $user['username'];
	else 
		return '';
}
function get_userpwd($username){
	$ps7=$db->prepare("SELECT `pwd` FROM `users` WHERE `username`=:username");
	$ps7->bindValue(':username',$username);
	return $ps7->fetch();
}
function get_uid($username){
	global $db;
	$ps=$db->prepare("SELECT `id` FROM `users` WHERE `username`=? ");
	$ps->execute(array($username));
	$uid=$ps->fetch();
	return $uid;
}

function get_pid($uid){
	global $db;
	$ps=$db->prepare("SELECT `id` FROM `post` WHERE `uid`=? order BY id DESC LIMIT 1" );
	$ps->execute(array($uid));
	$pid=$ps->fetch();
	return $pid['id'];
}
function  create_user($username, $pwd){
	global $db;
	$sha1pwd = sha1($pwd);

	$ps9=$db->prepare("INSERT INTO `users`(username,pwd) VALUES(?,?)");
	return $ps9->execute(array($username, $sha1pwd));
}

//判断用户名是否重复
function checkUsernameIsOK($username){
	global $db;

	$ps7=$db->prepare("SELECT count(*) as c FROM `users` WHERE `username`=?");
	$ps7->execute(array($username));
	$user = $ps7->fetch();

	if($user['c'] > 0){
		return false;
	}else{
		return true;
	}
}

//登陆
function login($username, $pwd){
	global $db;

	$sha1pwd = sha1($pwd);

	$sql = "SELECT id FROM `users` WHERE username=? and pwd=?";
	$ps7=$db->prepare($sql);
	$ps7->execute(array($username, $sha1pwd));
	$user = $ps7->fetch();

	if($user === false){
		return false;
	}

	return $user['id'];
}
?>